package com.yxly.yrdsqp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendAuth;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.platformtools.Log;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;
import com.yxly.Constants;

import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;


public class MainActivity extends UnityPlayerActivity {
    private IWXAPI api;
    private String furl;
    private  String openId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, true);
        api.registerApp(Constants.APP_ID);
    }


    public void WechatLogin()                           //微信登录请求 , 这步执行成功后会弹出微信
    {
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        api.sendReq(req);
    }

    public  void GetUserInfoReq(String token,String id)
    {
        openId = id;
        this.furl = "https://api.weixin.qq.com/sns/userinfo?access_token="+ token + "&openid=" + openId;
        HttpTread httpTread=new HttpTread();
        httpTread.start();
    }

    public class HttpTread extends Thread {    //向微信服务器发http请求
        public void run() {

            String param="";
            try {
                URL url = new URL(furl);
                HttpsURLConnection httpURLConnection = (HttpsURLConnection) url.openConnection();
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setConnectTimeout(10000);
                httpURLConnection.setRequestMethod("GET");
                httpURLConnection.connect();
                InputStreamReader bis = new InputStreamReader(httpURLConnection.getInputStream(),"utf-8");
                int c = 0;
                while((c = bis.read()) != -1){
                    param=param+(char)c;
                }
            }catch (Exception e) {
                Log.e("MainActivity",furl + "  HTTP通信失败");
                param = "http error";
            }
            if (param!="http error"){
                UnityPlayer.UnitySendMessage("GameManager", "WechatUserInfo", param);

            }
        }
    }
    //分享到微信
    public void  ShareToWeChat()
    {

    }

}
